package com.example.wnn.develop.dymcode;

import cn.hutool.core.codec.Base64;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class TestCode {

    public static void main(String[] args) {
        System.out.println("动态验证码开始生成："+System.currentTimeMillis());
        GifCaptcha gifCaptcha = new GifCaptcha(130, 48, 5);
        System.out.println(gifCaptcha.toBase64());
        System.out.println(	gifCaptcha.text().toLowerCase());
        System.out.println("动态验证码结束："+System.currentTimeMillis());

        System.out.println("静态验证码开始生成："+System.currentTimeMillis());
        //静态验证码 毫秒级别
        staticCode();
        System.out.println("静态验证码结束："+System.currentTimeMillis());

    }

    protected static void staticCode(){
        int width = 100;
        int height = 50;

        //创建一对象,在内存中图片（验证码图片对象）
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //填充背景色
        Graphics g = bufferedImage.getGraphics();   //画笔对象
        g.setColor(Color.pink); //画笔颜色
        g.fillRect(0, 0, width, height);

        //画边框
        g.setColor(Color.blue);
        g.drawRect(0, 0, width - 1, height - 1);

        String str = "123456789";
        //生成随机角标
        Random ran = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 5; i++) {
            int index = ran.nextInt(str.length());
            //获取字符
            char c = str.charAt(index);
            sb.append(c);
            Font font = new Font("Verdana", Font.PLAIN, 15);
            g.setFont(font);
            g.drawString(c + "", width / 5 * i, height / 2);
        }

        //画干扰线
        g.setColor(Color.green);

        //随机生成坐标点
        for (int i = 0; i < 10; i++) {
            int x1 = ran.nextInt(width);
            int x2 = ran.nextInt(width);
            int y1 = ran.nextInt(height);
            int y2 = ran.nextInt(height);
            g.drawLine(x1, y1, x2, y2);
        }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, "png", stream);
            String base64 = Base64.encode(stream.toByteArray());
            System.out.println("data:image/gif;base64,"+base64);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
